package org.clockworkmages.games.anno1186.situations.combat.options;

import java.util.List;

import org.clockworkmages.games.anno1186.GameBeansContext;
import org.clockworkmages.games.anno1186.GameDataService;
import org.clockworkmages.games.anno1186.GameState;
import org.clockworkmages.games.anno1186.GameStateService;
import org.clockworkmages.games.anno1186.TimeConstants;
import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter;
import org.clockworkmages.games.anno1186.model.character.PlayerCharacter;
import org.clockworkmages.games.anno1186.model.character.StatConstants;
import org.clockworkmages.games.anno1186.model.option.Option;
import org.clockworkmages.games.anno1186.model.situation.Situation;
import org.clockworkmages.games.anno1186.situations.combat.CombatSituation;
import org.clockworkmages.games.anno1186.situations.combat.CombatStatus;
import org.clockworkmages.games.anno1186.util.RollUtil;

public class FleeOption
		extends Option {

	private final boolean success;

	private final GameStateService gameStateService;
	private final GameDataService gameDataService;

	public FleeOption() {
		this.setConsumesCombatAction(true);
		this.setTimePassed(TimeConstants.COMBAT_TURN);

		gameDataService = GameBeansContext.getBean(GameDataService.class);
		gameStateService = GameBeansContext.getBean(GameStateService.class);
		GameState gameState = gameStateService.getGameState();

		NonPlayerCharacter enemy = gameStateService.getEnemy();
		PlayerCharacter me = gameState.getCharacter();

		int chance = RollUtil.chanceBase50(me
				.getBaseStatAsInt(StatConstants.AGILITY)
				- enemy.getBaseStatAsInt(StatConstants.AGILITY)) / 2;
		success = RollUtil.random(100) <= chance;

		this.setLabel("Flee (Agility, " + chance + "%)");

		if (!success) {
			this.setTextAfter("You don't manage to escape your enemy.");
		} else {
			this.setTextAfter("You have fled!");
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.clockworkmages.games.anno1186.model.option.Option#select()
	 */
	@Override
	public void select() {
		if (success) {
			CombatSituation combatSituation = gameStateService
					.getCurrentCombatSituation();
			combatSituation.setCombatStatus(CombatStatus.FLED);

			String fleeToSituationId = combatSituation.getEnemy().getFleeTo();
			if (fleeToSituationId != null) {
				// replace the Situation underlying the CombatSituation with the
				// Situation defined as fleeTo:
				Situation fleeToSituation = gameDataService.getGameData()
						.getSituations().get(fleeToSituationId);

				List<Situation> situationStack = gameStateService
						.getGameState().getSituationStack();
				situationStack.remove(situationStack.size() - 2);
				situationStack.add(situationStack.size() - 1, fleeToSituation);
			}
		}
		super.select();
	}

}
